<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

define('TAG_NAME' , 'name');
define('TAG_EXT' , 'extention');
define('TAG_CODE' , 'code');

function create_dir($path_name, $mode = 777, $recursive = true) {
    return mkdir($path_name, $mode, $recursive);
}

//supression d'un repertoire pleine 
function delTree($dir) {
    if (!is_dir($dir))
        return false;
    $files = array_diff(scandir($dir), array('.', '..'));
    foreach ($files as $file) {
        (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
    }
    return rmdir($dir);
}

//bool mkdir ( string  [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )
//vide un repertoire
function set_emty_dir($dir) {
    if (!is_dir($dir))
        return false;
    $files = array_diff(scandir($dir), array('.', '..'));
    foreach ($files as $file) {
        (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink($dir.$file);
    }
    return true;
}

// extraire un fichier zip situé sur $source dans $destination
function extract_zip_to($source, $destination) {
    $zip = new ZipArchive;
    if ($zip->open($source) === TRUE) {
        $zip->extractTo($destination);
        $zip->close();
        return true;
    } else {
        return false;
    }
}

//Ramène la liste des nom du fichier .svg
function get_liste_names() {
    $CI = & get_instance();
    $CI->load->helper('directory');
    return directory_map(IMAGE_PATH);
}

// Creation de l'hierarchie a partire du codification (sous forme de tableur )
function create_tree($names) {

    $tree = array();
    sort($names, SORT_STRING);
    foreach ($names as $value) {
        $v = explode(' ', $value, 2);
        $num = $v[0];
        $separ_num = explode('.', $num);
        switch (count($separ_num)) {
            case 1:
                $tree[$separ_num[0]] = array($value);
                break;
            case 2;
                $tree[$separ_num[0]][$separ_num[1]] = array($value);
                break;
            case 3 :$tree[$separ_num[0]][$separ_num[1]][$separ_num[2]] = $value;
                break;
        }
    }

    return $tree;
}

function is_empty_dir($dir) {
    if (!is_readable($dir))
        return NULL;
    return (count(scandir($dir)) == 2);
}

// La liste des element du premier niveau
function get_list_items($tree) {
    $data = array();
    for ($i = 1; $i < count($tree); $i++) {
        $data[] = $tree[$i][0];
    }
    return $data;
}

// Création des liste Html a partire du resultat du fonction create_tree
function create_node($node) {
    $html = "";
    if (!isset($node) || !is_array($node))
        return $html;

    foreach ($node as $elt) {
        if (is_array($elt))
        {
            $id = end( explode('__', $elt[0]) );
            $menu_title = substr($elt[0] , 0 ,strlen($elt[0]) - strlen($id ) -2  ); // eliminer __id 
            $menu_title = end( explode(' ', $menu_title , 2)); // eliminer codification
            $html .= "<li>" . '<p>'.$menu_title.'</p>';
            $html .= "<textarea cols='25' rows='1' id='".$id."' style='display:none' >$menu_title</textarea>";
            $elt = array_slice($elt, 1);
            if (count($elt) > 0)
                $html .= "<ul>" . create_node($elt) . "</ul></li>";
        } else {
            $id = end( explode('__', $elt) );
            $menu_title = substr($elt , 0 ,strlen($elt) - strlen($id) - 2 ); // eliminer __id
             $menu_title = end( explode(' ', $menu_title , 2)); // eliminer codification
            $html .= "<li>" . "<p>".$menu_title."</p>" ;
            $html .= "<textarea cols='25' rows='1' id='".$id."' style='display:none' >$menu_title</textarea></li>\n";
        }
    }

    return $html;
}

function get_default_elemnt() {
    $names = get_liste_names();
    foreach ($names as $elt) {
        $elt = trim($elt);
        if ($elt[0] === "0") {
			$t = explode(' ', $elt, 2);
            $e = $t[1];
            return split_name($e , TAG_NAME );
        }
    }
}

// creation du menu html
function create_navigation_menu($tree) {
    return "<ul>" . create_node($tree) . "</ul>";
}

function navigation_menu() {
    $list = create_tree(get_liste_names());
    return create_navigation_menu($list);
}

// ajoute les lien au contenu html
function create_linked_node($node) {
    $html = "";
    if (!isset($node) || !is_array($node))
        return $html;
    foreach ($node as $elt) {
        if (is_array($elt)) {
            $elt[0] = trim($elt[0]);
            $e = end(explode(" ",trim( $elt[0] ) , 2) );
            $html .= "<li><a href='ressources/" . split_name($e ,TAG_NAME ) . ".html' target='frame_slide'>" . get_menu_title( $elt[0]) . "</a>";

            $elt = array_slice($elt, 1);
            if (count($elt) > 0)
                $html .= "<ul>" . create_linked_node($elt) . "</ul></li>";
            else
            	$html .= "</li>";
        } else {
            $elt = trim($elt);
            $e = end(explode(" ", $elt , 2) );

            $html .= "<li><a href='ressources/" . split_name($e , TAG_NAME ) . ".html' target='frame_slide' >" . get_menu_title( $elt) . "</a></li>";
        }
    }

    return $html;
}
function get_menu_title($menu_code)
{
    $ci = &get_instance();
    $ci->load->model('menu_model' , 'menu');
    $t= $ci->menu->get_by(array('code',$menu_code));
	return $t['0']['title'];
}

// creation du menu de navigaton 
function get_linked_nav_menu( $attr = null) {
    $list = create_tree(get_liste_names() );
    $list = create_linked_node($list);
    $ul = "<ul ";
    if ($attr !== null && is_array($attr))
        foreach ($attr as $key => $v) {
            $ul .= " $key=\"" . $v . "\" ";
        }
    $ul .= " >" . $list . "</ul>";
    return $ul;
}

function download_zip_file($file) { // $file = include path 
    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
    }
}

function create_attachment_menu($names) {
    $tree = create_tree($names);
    $ret = get_list_items($tree);
    return $ret;
}

function getAttachment() {
    $CI = & get_instance();
    $CI->load->helper(array('my_file', 'directory', 'file'));

    $mapdirofattachment = directory_map(IMAGE_PATH, 1);

    // $menu = create_attachment_menu($mapdirofattachment);
    // var_dump($mapdirofattachment);
    $menuprincipale = get_lvl1_names();
    //var_dump($menu);
    $attachment_tree = array();
    foreach ($menuprincipale as $mp) {
        $node = array();
        $mp = trim($mp);
        $node['menu'] = $mp;
        $node['attach'] = array();

        foreach ($mapdirofattachment as $sousmenu) {
            $sousmenu = trim($sousmenu);
            if ($mp !== $sousmenu) {
                if (substr($mp, 0, 1) == substr($sousmenu, 0, 1)) {
                    $node['attach'][] = $sousmenu;
                }
            }
        }
        $attachment_tree[] = $node;
    }
    return $attachment_tree;
}

function get_lvl1_names() {
    $names = get_liste_names();
    $ret = array();
    foreach ($names as $n) {
        $n = trim($n);
        $t = explode(" ", $n);
		$num =  $t[0];
        if (!contain_char($num, '.'))
            $ret[] = $n;
    }
    return $ret;
}

function contain_char($str, $c) {
    for ($i = 0; $i < strlen($str); $i++) {
        if ($c === $str[$i])
            return TRUE;
    }
    return FALSE;
}

function wd_remove_accents($str, $charset = 'utf-8') {
    $str = htmlentities($str, ENT_NOQUOTES, $charset);
    $str = preg_replace('#&([A-za-z])(?:acute|cedil|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $str);
    $str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str); // pour les ligatures e.g. '&oelig;'
    $str = preg_replace('#&[^;]+;#', '', $str); // supprime les autres caractères

    return $str;
}

function clean_name($name)
{
    $ret = "";
    for($i = 0 ; $i < strlen($name); $i++)
    {
        $chars = array( ' ','.',',','\'','"');
        if(array_search($name[$i], $chars) !== FALSE)
        {
            $ret .= $name[$i];
            continue;
        }
        
        if( ($name[$i] >= 'A' && $name[$i] <= 'Z') || ($name[$i] >= 'a' && $name[$i] <= 'z') || ($name[$i] >= '0' && $name[$i] <= '9') )  
        {
           $ret .= $name[$i]; 
        }
    }
    return $ret;
}

function split_name($name , $tag = null)
{
    $ret = array();
    $ret[TAG_EXT] = end(explode('.',$name) );
     $t = explode(' ' , $name , 2);
	 $ret[TAG_CODE] =$t[0];
    $v = implode('.', explode('.', $name , -1) );
    $ret[TAG_NAME] = end(explode(' ',$v , 2));
    if($tag !== null)
        return $ret[$tag];
    return $ret;
    
}
